<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-refund-processing">
    <view class="refund-status">
      <view class="refund-status-title">
        退款状态：
      </view>
      <view
        v-if="platInterveneSts && platInterveneSts!==-1"
        class="refund-status-text"
      >
        <!-- 平台介入状态:(1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功 -1.没有介入) -->
        {{ platStatus[platInterveneSts] }}
      </view>
      <view
        v-else
        class="refund-status-text"
      >
        <!-- 1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭 -->
        {{ orderStatus[refundInfo.returnMoneySts + ''] }}
      </view>
    </view>
    <view
      v-if="platInterveneSts===1 && stillAveTime"
      class="plat-tips"
    >
      用户申请平台介入售后，请在{{ refundInfo.interventionEndTime }}前补充凭证
    </view>

    <!-- 退款进度 -->
    <view
      class="refund-progress text-arrow"
      @tap="showRefundProgress = true"
    >
      退款进度
    </view>
    <view class="prod-list">
      <view class="module-title">
        退款商品
      </view>
      <view
        v-for="(prod, index) in refundInfo.orderItems"
        :key="index"
        class="prod-list-item"
      >
        <view class="prod-common">
          <view class="prod-image">
            <img-show :src="prod.pic" />
          </view>
          <view class="prod-info">
            <view class="prod-name">
              {{ prod.prodName }}
            </view>
            <view class="refund-number">
              退款数量：
              <text v-if="refundInfo.refundType === 1">
                {{ prod.prodCount }}
              </text>
              <text v-if="refundInfo.refundType === 2">
                {{ refundInfo.goodsNum }}
              </text>
            </view>
          </view>
        </view>
        <!-- 赠品：多个商品时展示 -->
        <view v-if="refundInfo.orderItems.length > 1 && prod.giveawayList">
          <view
            v-for="giftItem in prod.giveawayList"
            :key="giftItem.orderItemId"
            class="prod-gift"
          >
            <text class="name">
              【赠品】{{ giftItem.prodName }}
            </text>
            <text>×{{ giftItem.prodCount }}</text>
          </view>
        </view>
      </view>
      <!-- 赠品：单个商品时展示 -->
      <view v-if="refundInfo.orderItems && refundInfo.orderItems.length === 1 && refundInfo.orderItems[0].giveawayList">
        <view
          v-for="item in refundInfo.orderItems[0].giveawayList"
          :key="item.orderItemId"
          class="prod-list-item"
        >
          <view class="prod-common">
            <view class="prod-image">
              <img-show :src="item.pic" />
            </view>
            <view class="prod-info">
              <view class="prod-name">
                {{ item.prodName }}
              </view>
              <view class="refund-gift">
                <view class="gift">
                  赠品
                </view>
                <view class="num">
                  x{{ item.prodCount }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="detail">
      <view class="module-title">
        退款详情
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          退款类型：
        </view>
        <view
          v-if="refundInfo.refundType === 1"
          class="detail-item-content"
        >
          整单退款
        </view>
        <view
          v-if="refundInfo.refundType === 2"
          class="detail-item-content"
        >
          单个物品退款
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          退款方式：
        </view>
        <view
          v-if="refundInfo.applyType === 1"
          class="detail-item-content"
        >
          仅退款
        </view>
        <view
          v-if="refundInfo.applyType === 2"
          class="detail-item-content"
        >
          退款退货
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          订单编号：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.orderNumber }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          退款编号：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.refundSn }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          实付金额：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.orderAmount }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          申请退款：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.refundAmount + "元+ " + refundInfo.refundScore + '积分' }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          申请时间：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.applyTime }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          退款原因：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.buyerReason }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          退款说明：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.buyerDesc }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          退款凭证：
        </view>
        <view class="detail-item-imgs">
          <view
            v-for="(rpic, indexp) in photoFiles"
            :key="indexp"
            class="img"
          >
            <img-show
              :src="rpic"
              @handle-tap="()=>refundPicPreView(photoFiles, indexp)"
            />
          </view>
        </view>
      </view>
    </view>
    <view
      v-if="refundInfo.refundDelivery && (refundInfo.refundDelivery.deyNu || refundInfo.refundDelivery.imgs)"
      class="detail"
    >
      <view class="module-title">
        物流详情
      </view>
      <view
        v-if="refundInfo.refundDelivery && refundInfo.refundDelivery.deyName"
        class="detail-item"
      >
        <view class="detail-item-title">
          物流名称：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.refundDelivery.deyName }}
        </view>
      </view>
      <view class="detail-item">
        <view
          v-if="refundInfo.refundDelivery && refundInfo.refundDelivery.deyNu"
          class="detail-item-title"
        >
          快递单号：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.refundDelivery.deyNu }}
        </view>
      </view>
      <view class="detail-item">
        <view
          v-if="refundInfo.refundDelivery && refundInfo.refundDelivery.senderRemarks"
          class="detail-item-title"
        >
          买家备注：
        </view>
        <view class="detail-item-content">
          {{ refundInfo.refundDelivery.senderRemarks }}
        </view>
      </view>
      <view class="detail-item">
        <view class="detail-item-title">
          物流凭证：
        </view>
        <view class="detail-item-imgs">
          <view
            v-for="(picl, indexl) in logisticsImgs"
            :key="indexl"
            class="img"
          >
            <img-show
              :src="picl"
              @handletap="()=>refundPicPreView(logisticsImgs, indexl)"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="refund-operation">
      <view
        v-if="refundInfo.returnMoneySts === 1"
        class="item"
        @tap="showSelect3=true"
      >
        <view class="item-left">
          申请审批
        </view>
        <view class="item-right">
          {{ agreeRefund[findAgreeRefund].name }}
        </view>
      </view>
      <view
        v-if="refundInfo.returnMoneySts === 1"
        class="line-split"
      />
      <view
        v-if="refundInfo.applyType === 2 && isAgreeRefund === 1 && refundInfo.returnMoneySts !== -1"
        class="item"
        @tap="refundInfo.returnMoneySts === 1 ? showSelect4=true : ''"
      >
        <view class="item-left">
          收货地址
        </view>
        <view
          v-if="refundInfo.returnMoneySts === 1"
          class="item-right addrWidth"
        >
          {{ addrList[findAddr].name }}
        </view>
        <view
          v-if="refundInfo.refundDelivery.receiverAddr"
          class="item addrWidth"
        >
          {{ refundInfo.refundDelivery.receiverName +'，'+refundInfo.refundDelivery.receiverMobile+'，'+refundInfo.refundDelivery.receiverAddr }}
        </view>
      </view>
      <view
        v-if="refundInfo.applyType === 2 && isAgreeRefund === 1 && refundInfo.returnMoneySts !== -1"
        class="line-split"
      />
      <view
        v-if="refundInfo.shipTime &&!refundInfo.cancelTime &&!refundInfo.rejectTime"
        class="item"
        @tap="refundInfo.returnMoneySts === 3 ? showSelect1=true : ''"
      >
        <view class="item-left">
          退货状态
        </view>
        <view :class="[refundInfo.returnMoneySts === 3 ? 'item-right' : '']">
          {{ refundStutus[findReceiving].name }}
        </view>
      </view>
      <view
        v-if="refundInfo.shipTime &&!refundInfo.cancelTime &&!refundInfo.rejectTime"
        class="line-split"
      />
      <view
        v-if="refundInfo.shipTime &&!refundInfo.cancelTime &&!refundInfo.rejectTime"
        class="item"
        @tap="refundInfo.returnMoneySts === 3 ? showSelect2=true : ''"
      >
        <view class="item-left">
          退货申请
        </view>
        <view :class="[refundInfo.returnMoneySts === 3 ? 'item-right' : '']">
          {{ returnApplications[findApplication].name }}
        </view>
      </view>
      <view
        v-if="refundInfo.shipTime &&!refundInfo.cancelTime &&!refundInfo.rejectTime"
        class="line-split"
      />
      <view
        v-if="isAgreeRefund === 0"
        class="item"
      >
        <view class="item-left">
          拒绝原因<span class="red">*</span>
        </view>
        <view class="item-input">
          <input
            v-model="refundInfo.rejectMessage"
            maxlength="250"
            class="input"
            type="text"
            placeholder="请输入拒绝理由"
          >
        </view>
      </view>
      <view
        v-if="isAgreeRefund === 0"
        class="line-split"
      />
      <view
        v-if="isAgreeRefund === 0"
        class="item voucher-con"
      >
        <view class="item-left">
          上传凭证<span class="red">*</span>
        </view>
        <imgs-upload
          v-model="refundInfo.voucherImgs"
          :img-num="3"
          :sty="{width:'120rpx',height:'120rpx'}"
          upload-pos="right"
        />
      </view>
      <view
        v-if="isAgreeRefund === 0"
        class="line-split"
      />
      <view
        v-if="refundInfo.returnMoneySts === 1"
        class="item"
      >
        <view class="item-left">
          商家备注
        </view>
        <view
          v-if="refundInfo.returnMoneySts === 1"
          class="item-input"
        >
          <input
            v-model="refundInfo.sellerMsg"
            maxlength="250"
            class="input"
            type="text"
            placeholder="商家备注"
          >
        </view>
      </view>
    </view>
    <view style="height: 120rpx;" />
    <view
      v-if="refundInfo.returnMoneySts === 1 || refundInfo.returnMoneySts === 3 || (platInterveneSts===1&&stillAveTime)"
      class="refund-footer"
    >
      <view
        v-if="refundInfo.returnMoneySts === 1 || refundInfo.returnMoneySts === 3"
        class="refund-btn"
        @tap="refundInfo.returnMoneySts === 1 ? checkHandel() : returnMoneyHandle()"
      >
        确定
      </view>
      <view
        v-if="platInterveneSts===1 && stillAveTime"
        class="refund-btn"
        @tap="addProofShow = true"
      >
        补充凭证
      </view>
    </view>
    <select-popup
      v-if="showSelect1"
      :value="isReceiving"
      :data="refundStutus"
      @submit-data="getRefundStutu"
      @cancal="cancal"
    />
    <select-popup
      v-if="showSelect2"
      :value="isAgreeRefund"
      :data="returnApplications"
      @submit-data="getRefundStutu"
      @cancal="cancal"
    />
    <select-popup
      v-if="showSelect3"
      :value="isAgreeRefund"
      :data="agreeRefund"
      @submit-data="getRefundStutu"
      @cancal="cancal"
    />
    <select-popup
      v-if="showSelect4"
      :value="refundInfo.refundAddrId"
      :data="addrList"
      @submit-data="getRefundStutu"
      @cancal="cancal"
    />

    <!-- 添加凭证弹窗 -->
    <add-proof-popup
      v-model="addProofShow"
      :refund-detail="refundInfo"
      @change-data="getOrderInfo"
    />

    <!-- 退款进度弹窗 -->
    <refund-progress
      v-model="showRefundProgress"
      :refund-detail="refundInfo"
    />
  </view>
</template>

<script setup>
import addProofPopup from '@/components/add-proof-popup/index.vue'
import refundProgress from '@/components/refund-progress/index.vue'
import util from '@/utils/util'
const showRefundProgress = ref(false)
const addProofShow = ref(false)

const refundStutus = [
  {
    name: '已收货',
    value: 1
  },
  {
    name: '未收货',
    value: 0
  }
]
const returnApplications = [
  {
    name: '同意退款',
    value: 1
  },
  {
    name: '拒绝退款',
    value: 0
  }
]
const agreeRefund = [
  {
    name: '同意退款',
    value: 1
  },
  {
    name: '不同意',
    value: 0
  }
]
const orderStatus = { 1: '买家申请', 2: '卖家接受', 3: '买家发货', 4: '卖家收货', 5: '退款成功', 6: '买家撤回申请', 7: '商家拒绝', '-1': '退款关闭' }
const platStatus = ['', '平台介入中', '平台介入中', '平台拒绝退款', '', '退款成功']
// 是否收到货
const isReceiving = ref(0)
// 是否同意申请审批
const isAgreeRefund = ref(1)
const addrList = reactive([{ name: '请选择', value: 0 }]) // 收获地址
let isProcessing = false // 是否正在处理订单
let isUploadInvoice = false
const showSelect1 = ref(false)
const showSelect2 = ref(false)
const showSelect3 = ref(false)
const showSelect4 = ref(false)
let refundId = ''
const photoFiles = ref([])
const logisticsImgs = ref([])
const refundInfo = ref({})
onLoad((options) => {
  refundId = options.refundId
  // eslint-disable-next-line no-unused-vars
  Promise.all([getOrderInfo(), getRefundAddrList()]).then(([param1, param2]) => {
    if (param2) {
      nextTick(() => {
        refundInfo.value.refundAddrId = param2
      })
    }
  })
})

onUnload(() => {
  intervenEndTimer && clearTimeout(intervenEndTimer)
})

const findReceiving = computed(() => {
  const index = refundStutus.findIndex(item => item.value === isReceiving.value)
  return index
})
const findApplication = computed(() => {
  const index = returnApplications.findIndex(item => item.value === isAgreeRefund.value)
  return index
})
const findAgreeRefund = computed(() => {
  const index = agreeRefund.findIndex(item => item.value === isAgreeRefund.value)
  return index
})
const findAddr = computed(() => {
  const index = addrList.findIndex(item => item.value === refundInfo.value.refundAddrId)
  return index
})

const platInterveneSts = ref(0)
const getOrderInfo = () => {
  photoFiles.value = []
  logisticsImgs.value = []
  const params = {
    url: `/order/refund/info/${refundId}`,
    method: 'GET'
  }
  return http.request(params).then(({ data: res }) => {
    if (res.refundDelivery.imgs !== null) {
      logisticsImgs.value = res.refundDelivery.imgs.split(',')
    }
    if (res.photoFiles && res.photoFiles.imgs !== null) {
      photoFiles.value = res.photoFiles.split(',')
    }

    res.refundAddrId = 0
    agreeRefund[0].name = res.applyType !== 1 ? '同意退货退款' : '同意退款'
    isReceiving.value = res.isReceiver ? 1 : 0
    isAgreeRefund.value = 1
    getIsInvoiceUpload(res.orderNumber)
    refundInfo.value = res
    platInterveneSts.value = res.platformInterventionStatus
    if (res.interventionEndTime && platInterveneSts.value === 1) {
      intervenEndTimeCountdown()
    }
  })
}

// 平台介入时间添加凭证倒计时
let intervenEndTimer = null
const stillAveTime = ref(false)
const intervenEndTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(refundInfo.value.interventionEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    stillAveTime.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenEndTimer = setTimeout(intervenEndTimeCountdown, 1000)
  } else {
    stillAveTime.value = false
    intervenEndTimer && clearTimeout(intervenEndTimer)
  }
}

/**
 * 退款凭证 图片点击预览
 * @param {Array} list 数组
 * @param {Number} index 索引
 */
const refundPicPreView = (list, index) => {
  uni.previewImage({
    current: index,
    urls: list.map(el => util.checkFileUrl(el))
  })
}
const getRefundStutu = (vaule) => {
  if (showSelect1.value) {
    isReceiving.value = vaule
    showSelect1.value = false
  }
  if (showSelect2.value) {
    isAgreeRefund.value = vaule
    showSelect2.value = false
  }
  if (showSelect3.value) {
    isAgreeRefund.value = vaule
    showSelect3.value = false
  }
  if (showSelect4.value) {
    refundInfo.value.refundAddrId = vaule
    showSelect4.value = false
  }
}
const cancal = () => {
  showSelect1.value = false
  showSelect2.value = false
  showSelect3.value = false
  showSelect4.value = false
}
const getIsInvoiceUpload = (orderNumber) => {
  const params = {
    url: '/m/orderInvoice/is_upload',
    method: 'GET',
    data: {
      orderNumber
    }
  }
  http.request(params).then(({ data: res }) => {
    isUploadInvoice = res
  })
}
// 仅退款
const checkHandel = () => {
  if (isAgreeRefund.value === 1) {
    if (isUploadInvoice) {
      uni.showModal({
        title: '提示',
        content: '该订单已上传发票，确认退款后请前往PC端查看并处理已上传发票的内容。',
        cancelText: '取消',
        confirmText: '确定',
        success (res) {
          if (res.confirm) {
            if (refundInfo.value.refundType === 2 && refundInfo.value.applyType === 1 && refundInfo.value.status === 2) {
              checkIsLastOrderItem(handelReturnMoney())
              return
            }
            handelReturnMoney()
          }
        }
      })
      return
    } else {
      if (refundInfo.value.refundType === 2 && refundInfo.value.applyType === 1 && refundInfo.value.status === 2) {
        checkIsLastOrderItem(handelReturnMoney)
        return
      }
      handelReturnMoney()
    }
    return
  }
  handelReturnMoney()
}
// 退货退款
const returnMoneyHandle = () => {
  if (isProcessing) {
    return
  }
  if (isAgreeRefund.value === 0) {
    if (!refundInfo.value.rejectMessage?.trim()) {
      uni.showToast({
        title: '拒绝原因不能为空',
        mask: false,
        icon: 'none',
        duration: 1000
      })
      return
    }
    if (!refundInfo.value.voucherImgs) {
      uni.showToast({
        title: '请上传凭证',
        mask: false,
        icon: 'none',
        duration: 1000
      })
      return
    }
  }
  isProcessing = true
  isAgreeRefund.value !== 0 && (refundInfo.value.voucherImgs = '')
  const params = {
    url: '/order/refund/returnMoney',
    method: 'put',
    data: {
      refundId: refundInfo.value.refundId,
      refundSts: isAgreeRefund.value === 1 ? 2 : 3,
      refundSn: refundInfo.value.refundSn,
      rejectMessage: refundInfo.value.rejectMessage,
      sellerMsg: refundInfo.value.sellerMsg,
      isReceiver: isReceiving.value,
      shopImgUrls: refundInfo.value.voucherImgs // 凭证
    },
    hasCatch: true
  }
  http.request(params).then(() => {
    refundInfo.value.voucherImgs = ''
    isProcessing = false
    getOrderInfo()
    uni.showToast({
      title: '操作成功',
      mask: false,
      icon: 'none',
      duration: 1000
    })
  }).catch(() => {
    isProcessing = false
  })
}
const handelReturnMoney = () => {
  const tempRefundAddrId = isAgreeRefund.value === 1 ? refundInfo.value.refundAddrId : undefined
  if (isProcessing) {
    return
  }
  if (isAgreeRefund.value === 0) {
    if (!refundInfo.value.rejectMessage?.trim()) {
      uni.showToast({
        title: '拒绝原因不能为空',
        mask: false,
        icon: 'none',
        duration: 1000
      })
      return
    }
    if (!refundInfo.value.voucherImgs) {
      uni.showToast({
        title: '请上传凭证',
        mask: false,
        icon: 'none',
        duration: 1000
      })
      return
    }
  }
  isProcessing = true
  isAgreeRefund.value !== 0 && (refundInfo.value.voucherImgs = '')
  const params = {
    url: '/order/refund/process',
    method: 'put',
    data: {
      refundId: refundInfo.value.refundId,
      refundSts: isAgreeRefund.value === 1 ? 2 : 3,
      refundSn: refundInfo.value.refundSn,
      rejectMessage: refundInfo.value.rejectMessage,
      sellerMsg: refundInfo.value.sellerMsg,
      refundAddrId: tempRefundAddrId,
      shopImgUrls: refundInfo.value.voucherImgs // 凭证
    },
    hasCatch: true
  }
  http.request(params).then(() => {
    isProcessing = false
    refundInfo.value.voucherImgs = ''
    getOrderInfo()
    uni.showToast({
      title: '操作成功',
      mask: false,
      icon: 'none',
      duration: 1000
    })
  }).catch(res => {
    uni.showToast({
      title: res.msg,
      mask: false,
      icon: 'none',
      duration: 1000
    })
    isProcessing = false
  })
}
/**
 * 加载收货地址模板
 */
const getRefundAddrList = () => {
  const params = {
    url: '/shop/refundAddr/list',
    method: 'GET'
  }
  return http.request(params).then(({ data: res }) => {
    let defaultRefundAddrId
    res.forEach(x => {
      addrList.push({ name: x.receiverName + '，' + x.receiverMobile + '，' + x.province + x.city + x.area + x.addr, value: x.refundAddrId })
      if (x.defaultAddr) {
        defaultRefundAddrId = x.refundAddrId
      }
    })
    return defaultRefundAddrId
  })
}
// 是否为最后一个退款项
const checkIsLastOrderItem = (fn) => {
  const params = {
    url: '/order/refund/isLastRefund',
    method: 'GET',
    data: {
      refundSn: refundInfo.value.refundSn
    }
  }
  http.request(params).then(({ data: res }) => {
    if (res && refundInfo.value.freightAmount) {
      uni.showModal({
        title: '提示',
        content: `该退款申请项是订单中最后一件商品，同意退款后运费￥${refundInfo.value.freightAmount.toFixed(2)}会一并退还给用户`,
        cancelText: '取消',
        confirmText: '确定',
        success (res) {
          if (res.confirm) {
            fn()
          }
        }
      })
    } else {
      fn()
    }
  })
}
</script>

<style lang="scss" scoped>
@use "./refund-processing.scss";
</style>
